<!DOCTYPE html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加订单</title>
    <link rel="stylesheet" href="<%=basePath %>web/themes/icon.css">
    <link rel="stylesheet" href="<%=basePath %>web/themes/default/easyui.css">
    <link rel="stylesheet" href="<%=basePath %>web/css/wu.css">
	<script src="<%=basePath %>web/js/jquery.min.js"></script>
    <script src="<%=basePath %>web/js/jquery.easyui.min.js"></script>
    <script src="<%=basePath %>web/js/easyui-lang-zh_CN.js"></script>
    <script>
    	$(function(){
    		var path=$("#path").val();
    		 $("#generatingParts").datagrid({
                url:path+'part/getByCode',
                queryParams:{code:$("#code").val()},
                checkOnSelect:true,
                rownumbers:true,
                columns:[[
                    {field:'code',title:'询价编号',width:130},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:100},
                    {field:'partNo',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:100,
                    	 formatter:function(value,row,index){
                            return '<input type="number" name="amount" onchange="change_amount_sellPrice('+index+',this)" value="'+value+'" min="1" style="width:50px;"/>';
                        }
                    },
                    {field:'avg',title:'单价￥',width:100, 
                        formatter:function(value,row,index){
                        	if(row.sellPrice==null){
                        		return "";
                        	}
                            return '<input type="number" name="avg" onchange="change_amount_sellPrice('+index+',this)" value="'+row.price/row.amount+'" min="1" style="width:50px;"/>';
                        }
                    },
                    {field:'price',title:'总金额￥',width:100,
                         formatter:function(value,row,index){
                            return "￥"+row.price;
                        }
                    },
                    {field:'pd_memo',title:'备注',width:100,
	                    formatter:function(value,row,index){
		                     if(row.sellPrice==null){
		                    	return null;
		                      }
		                      if(value==null || value=='')
		                      value='';
	                         return '<input name="memo" onchange="onChange_Memo('+index+',this)" type="text" value="'+value+'" style="width:80px;"/>';
	                      }
	                 }, 
                    {field:'sePrice',title:'上次价格￥',width:100,
                    formatter:function(value,row,index){
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            return ""+row.sellPrice;
                        }
                    },
                       {field:'opt',title:'操作',width:100,formatter:function (value,row,index) {
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            var context="<a href=\"javascript:del('"+index+"')\" style='color:blue;text-decoration:underline;'>删除</a>&nbsp;&nbsp;" 
                            return context;
                        }}

                ]],
                 onClickRow:function(index,data){
                	$(this).datagrid('unselectRow',index);
                },
                onLoadSuccess:function(){
               		oldRow=$("#generatingParts").datagrid('getRows');
               		if(oldRow[oldRow.length-1].sellPrice!=null){
                	$("#generatingParts").datagrid('appendRow',{
                	'partBrand':"合计",
                	'amount':total('amount'),
                	'price':total('price')
                	});
               		}
                }
             });
               $("#check").click(function(){
               		$.messager.confirm('审核状态','您确认审核?',function(r){    
					    if (r){ 
							var oldRow=$('#generatingParts').datagrid('getRows');
					    	var f=$("#form").serialize();
					    	var de=$("#deliveryTime").textbox('getText');
					    	var checkStatus=2;
					    	var code=$("#code").val();
					    	var data =JSON.stringify($('#generatingParts').datagrid('getData').rows);
					    	if(de==null || de==''){
					    		$.messager.alert('我的消息','请填写交货时间!','warning');
					    	}else{
						    	if(oldRow==null||oldRow==''){
					        		$.messager.alert('我的消息','没有填写配件信息!','warning');
						    	}else{
						     	var money=parseFloat(oldRow[oldRow.length-1]['price']);
									 $.ajax({
										type:"get",//请求类型
										url:path+"PurchaseOrderBill/updatePOB?"+f, 
										dataType:"json",//ajax接口（请求url）返回的数据类型
										data:{'data':data,'money':money},
										success:function(data){//data：返回数据（json对象）
										   if(data=="y"){
										   }else{
										   	   alert("审核过程数据异常!");
										   }
										}
							        }); 
								    $.ajax({
												type:"get",//请求类型
												url:path+"PurchaseOrderBill/modifyPurchaseOrderBillByCode", 
												dataType:"json",//ajax接口（请求url）返回的数据类型
												data:{'code':code,'checkStatus':checkStatus},
												success:function(data){//data：返回数据（json对象）
													if(data.result=="noPower"){
								   						alert("您没有权限!");
								  					 }else{
														if(data.flag=="y"){
															 location.href=path+"PurchaseOrderBill/getByCodeUpdate?code="+data.code+"&num="+data.checkStatus+"";
														}else{
														 alert("审核失败!");
														}
													}
											}
										});  
							    }
					    	}
						}
					})   
               		
               })
               $("#save").click(function(){
			  	 $.messager.confirm('修改消息','您确认修改吗?',function(r){    
					  if (r){    
			   		var oldRow=$('#generatingParts').datagrid('getRows');
			    	var f=$("#form").serialize();
			    	var de=$("#deliveryTime").textbox('getText');
			    	var data =JSON.stringify($('#generatingParts').datagrid('getData').rows);
			    	if(de==null || de==''){
			    		$.messager.alert('我的消息','请填写交货时间!','warning');
			    	}else{
				    	if(oldRow==null||oldRow==''){
			        		$.messager.alert('我的消息','没有填写配件信息!','warning');
				    	}else{
				    	var money=parseFloat(oldRow[oldRow.length-1]['price']);
							 $.ajax({
								type:"get",//请求类型
								url:path+"PurchaseOrderBill/updatePOB?"+f, 
								dataType:"json",//ajax接口（请求url）返回的数据类型
								data:{'data':data,'money':money},
								success:function(data){//data：返回数据（json对象）
								   if(data.result=="noPower"){
								   	alert("您没有权限!");
								   }else{
									   if(data=="y"){
									      alert("修改成功!");
									      parent.addTabs('修改订单',path+'web/goods/purchaseOrderBill.jsp');
									   }else{
									   	   alert("修改失败!");
									   }
								   }
								}
					        });
					    }
			    	}     
					    }   
					});
			   })
    	})
    	   function closeSupplier(){
        	$("#partList").dialog("destroy");
        	$("#part_List_parent").html("<div id='partList'  style='display: none' data-options='onClose:function(){closeSupplier()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_Part.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        function loadPart() {
        	if(!$("#supplierName").textbox('getText')){
        	 $.messager.alert('我的消息','供应商名称不能为空!','warning');
        	 return;
        	}
            $("#partList").dialog({
                title: '选择配件',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })
        } 
          function closePart() {
            $("#partList").dialog("close");
        }
         function closeDg(name) {
            $("#supplierName").val(name);
            $("#list").dialog("close");
        }
    	 function total(col){
        	var rows=$("#generatingParts").datagrid('getRows');
        	var total=0;
        	for(var i=0;i<rows.length;i++){
        		total+=parseFloat(rows[i][col]);
        	}
        	return total;
        }
            //用于将子页面的数据绑定到相关元素上
        function bindValue(data){
        	var name=data[0];
        	var linkman=data[1];
        	var phone=data[2];
        	var fax=data[3];
        	$('#supplierName').textbox('setValue',name);	
        	$('#contacter').textbox('setValue',linkman);	
        	$('#phone').textbox('setValue',phone);	
        	$('#fax').textbox('setValue',fax);	
        }
   
        function closeSon(){
        	 $("#list").dialog("destroy");
        	 $("#absolute").html("<div id='list'  style='display: none' data-options='onClose:function(){closeSon()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_supplier.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        function add(){
        var path=$("#path").val();
          	parent.addTabs("添加订单",path+"web/goods/addOrderBill.jsp");
   
        }    
          function loadSupplier() {
            $("#list").dialog({
                title: '供应商列表,双击可选中',
                width: 905,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })    
        }
     	//修改
 		//用于将子页面的数据绑定到相关元素上
         function addpart(row){
            var flag=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']){
         		        $.messager.alert('我的消息','不能添加重复配件!','warning');
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==false){
                 	break;
                 }
                }
             }
             if(flag==true){
                 for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i]);
                 }
              }
              closePart();
         }
        
        function addToPage(row){
           $('#generatingParts').datagrid('appendRow',{
           		
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: 1,
				sellPrice: row.sellPrice,
				price: row.sellPrice,
				memo: row.memo,
				opt: row.opt
		   });
		   
		   $("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
          })
        }
             
          function change_amount_sellPrice(input_index,input){
         	var amount=$(input).parent().parent().parent().find('[name="amount"]').val();
         	var avg=$(input).parent().parent().parent().find('[name="avg"]').val();
         	var price=parseFloat(amount)*parseFloat(avg);
         	$('#generatingParts').datagrid('updateRow',{
				index: input_index,
				row: {
					amount: amount,
					avg:avg,
					price: price
				}
			});
			var oldRow=$('#generatingParts').datagrid('getRows');
			$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
         }
           
           function onChange_Memo(index,input){
             var memo=$(input).parent().parent().parent().find('[name="memo"]').val();
          $("#generatingParts").datagrid('updateRow',{
               index: index,
	           row: {
		          pd_memo:memo
	           }
          });
          }
          
          function del(index){
         	//删除当前行
         	$('#generatingParts').datagrid('deleteRow',index);
         	//拿到之前的数据并重新封装，刷新index
         	var oldData=$('#generatingParts').datagrid('getData');
         	$('#generatingParts').datagrid('loadData',oldData);
         	//更新最后一行
         	var oldRow=$('#generatingParts').datagrid('getRows');
         	$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
           		if(oldRow.length==1){
          		$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
          	}
         }
          function loadInquiry() {
        	if(!$("#supplierName").textbox('getText')){
        	$.messager.alert('我的消息','供应商名称不能为空!','warning');
        	 return;
        	}
            $("#partList1").dialog({
                title: '选择询价单',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })
        } 
         function closeSupplier1(){
        	$("#partList1").dialog("destroy");
        	$("#part_List_parent1").html("<div id='partList1'  style='display: none' data-options='onClose:function(){closeSupplier1()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_inquirybill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
          function closePart1() {
            $("#partList1").dialog("close");
        }//用于将子页面的数据绑定到相关元素上
         function addpart1(row){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['billCode']==row[i]['billCode']){
         		       $.messager.alert('我的消息','不能重复添加询价配件','warning');
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addToPage1(row[i]);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage1(row[i]);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage1(row[i]);
					}	
                }
              }
              closePart1();
         }    
        function addToPage1(row){
           $('#generatingParts').datagrid('appendRow',{
           		billCode:row.billCode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: row.amount,
				sellPrice: row.sellPrice,
				price: row.sellPrice*row.amount,
				memo: row.memo,
				opt: row.opt
		   });
		   
		   $("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
          })
        }
        function loadClose(){
        	parent.closeTabs('修改订单')
        }
    </script>
    <style>
      body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
          border-collapse:collapse;
          border-spacing:0;
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
            border:1px solid #84a0c4 
        }
        
        
    </style>


</head>
<body>
<form name="form"  id="form" action="" method="post">
    <table cellpadding="0" cellspacing="0" class="l-table-edit" style="width:100%;" border="1">
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">订单编号：</td>
            <td width="27%" align="left" class="l-table-edit-td">
           	    <input  type="text" class="easyui-textbox" id="code" value="${list.code }" name="code" maxlength="100" ltype="text" style="height:20px" readonly="readonly" />
            </td>
            <td width="13%"  align="right" class="l-table-edit-td">订单日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input  type="text" id="addDate" name="orderTime" value="<fmt:formatDate value="${list.orderTime}" pattern="yyyy-MM-dd HH:mm:ss"/>" maxlength="30" class="easyui-datetimebox" style="height:20px" readonly="readonly"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="javascript:loadSupplier()" style="color: blue;text-decoration: underline;">供应商名：</a>
            </td>
            <td align="left" class="l-table-edit-td" width="27%">
      
                <input type="text" id="supplierName"  value="${list.supplierName }" name="supplierName" class="easyui-textbox"  maxlength="100" ltype="text"  style="height:20px" />
            
            <td width="13%" align="right" class="l-table-edit-td">联系人员：</td>
            <td align="left" class="l-table-edit-td" width="43%">
                <input  type="text" id="contacter" value="${list.linkman }" name="linkman" class="easyui-textbox" maxlength="30" ltype="text" style="height:20px" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电话：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" id="phone"class="easyui-textbox" value="${list.phone}" name="phone" maxlength="50" ltype="text" style="height:20px" /></td>
            <td width="13%" align="right" class="l-table-edit-td">传真：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text" id="fax" class="easyui-textbox" value="${list.company.fax }" name="fax" maxlength="50"  ltype="text" style="height:20px" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">运输方式：</td>
            <td width="27%" align="left" class="l-table-edit-td">
             <select name="shippingMode" id="shippingMode" class="easyui-combobox" style="width:100px;height:20px" panelHeight="150px" >
             		<c:if test="${list.shippingMode==1 }">
             		  	<option value="1" selected="selected">圆通快递</option> 
             		  	<option value="2" >中通快递</option> 
             		</c:if>
             		<c:if test="${list.shippingMode==2 }">
             			<option value="1" >圆通快递</option> 
             		  	<option value="2" selected="selected" >中通快递</option> 
             		</c:if>
             </select>
            </td>
            <td width="13%" align="right" class="l-table-edit-td">业务人员：</td>
            <td width="43%"align="left" class="l-table-edit-td"><input type="text"  class="easyui-textbox"  name="admin" id="admin" value="admin" maxlength="50"  ltype="text" style="height:20px" readonly="readonly"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">备注：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" class="easyui-textbox" id="type" value="${list.memo }" name="memo" maxlength="50" ltype="text" style="height:20px" /></td>
            <td width="13%" align="right" class="l-table-edit-td">交货日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text"  class="easyui-datetimebox" id="deliveryTime" value="<fmt:formatDate value="${list.deliveryTime}" pattern="yyyy-MM-dd HH:mm:ss"/>" name="deliveryTime" maxlength="50"  ltype="text" style="height:20px" /></td>
        </tr>
    </table>
</form>
<br>
<input type="hidden" id="path" value="<%=basePath%>"/>
<input  type="button" value="新   增" style="width:60px" onclick="add()">
<a href="javascript:loadInquiry()"><input  type="button" value="选询价单" style="width:60px" ></a>
<a href="javascript:loadPart()"><input  type="button" value="添加配件" style="width:60px" ></a>
<input  type="button" value="保存" style="width:60px" id="save">
<input  type="button" value="审核" style="width:60px" id="check">
<input  type="button" value="撤销" style="width:60px" id="backout" disabled="disabled">
<a href="javascript:loadClose()"><input  type="button" value="关闭" style="width:60px" ></a>
<br/><br/>
<div id="generatingParts" class="easyui-datagrid">

</div>
<div id="absolute">
	<div id="list"  style="display: none" data-options="onClose:function(){closeSon()}">
    	<iframe src='<%=basePath %>web/goods/purchaseOrderBill_supplier.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
<div id="part_List_parent">
	<div id="partList"  style="display: none" data-options='onClose:function(){closeSupplier()}'>
	    <iframe src='<%=basePath %>web/goods/purchaseOrderBill_Part.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
<div id="part_List_parent1">
	<div id="partList1"  style="display: none" data-options='onClose:function(){closeSupplier1()}'>
		 <iframe src='<%=basePath %>web/goods/purchaseOrderBill_inquirybill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
</body>
</html>